/*
 * Copyright 2008 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.ccsoft.mc.core.impl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.xml.XMLConstants;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.ccsoft.mc.core.ConfigTag;
import org.ccsoft.mc.core.Interceptor;
import org.ccsoft.mc.core.Property;
import org.ccsoft.mc.core.Reference;
import org.ccsoft.mc.core.Service;
import org.ccsoft.mc.core.ServiceBundle;
import org.ccsoft.mc.core.exceptions.LoadConfigException;
import org.ccsoft.mc.core.interceptor.impl.ServiceInterceptorProxy;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
/**
 * 
 * @author Chao Cai
 * 
 *Read and parse the config and according this create the ServiceBundles
 */

public class ConfigParser {
	List<ServiceBundle> bundles=new ArrayList<ServiceBundle>();
	class Elementhnd extends DefaultHandler{
		ServiceBundle currentBundle=null;
		Property currentProperty=null;
		Service currentService=null;
		
		private void dealComponentTag(Attributes attrs){
			currentBundle=new ServiceBundle();
			String name=attrs.getValue(ConfigTag.NAME);
			if (name!=null){
				currentBundle.setComponentName(name);				
			}
			String className=attrs.getValue(ConfigTag.CLASS);
			if (className!=null){
				try {
					Object instance=Class.forName(className).newInstance();
					currentBundle.setInstance(instance);
				} catch (Exception e) {
					throw new LoadConfigException("the component "+String.valueOf(name)+" create failed!",e);
				}				
			}
		}
		private void dealServiceTag(Attributes attrs){
			currentService=new Service();			
			String interfaceName=attrs.getValue(ConfigTag.INTERFACE);
			if (interfaceName!=null){
				currentService.setInterfaceName(interfaceName);	
			}else{
				throw new LoadConfigException("Component "+String.valueOf(currentBundle.getComponentName())
						+" contains the service not defined the interface!");
			}
			currentBundle.getServices().add(currentService);
		}
		private void dealFilterTag(Reference ref,String filter){
			if (filter!=null){
				ref.setComponentName(filter);
			}
		}
		private void dealInterceptorTag(Attributes attrs){
			String interceptor=attrs.getValue(ConfigTag.CLASS);
			this.currentService.getInterceptors().add(interceptor);
		}
		private void dealCardinalityTag(Reference ref,String cardinality){
			if (cardinality!=null){
				String [] parts=cardinality.split("\\.\\.");				
				try{
					if (parts[1].equals("n")){
						ref.setCardinalityMax(-1);
					}else{
						ref.setCardinalityMax(new Integer(parts[1]).intValue());
					}
				}catch(Exception e){
					throw new LoadConfigException("Component "+String.valueOf(currentBundle.getComponentName())
							+" contains the cardinality with wrong format!",e);
				}
			}
		}
		private void dealReferenceTag(Attributes attrs){
			Reference ref=new Reference();
			String filter=attrs.getValue(ConfigTag.FILTER);
			dealFilterTag(ref,filter);
			String interfaceName=attrs.getValue(ConfigTag.INTERFACE);
			if (interfaceName!=null){
				ref.setInterfaceName(interfaceName);
			}else{
				throw new LoadConfigException("Component "+String.valueOf(currentBundle.getComponentName())
						+" contains the reference not defined the interface!");
			}
			String bindProperty =attrs.getValue(ConfigTag.BIND_PROPERTY);
			if (bindProperty!=null){
				ref.setProperty(bindProperty);
			}else{
				throw new LoadConfigException("Component "+String.valueOf(currentBundle.getComponentName())
						+" contains the reference not defined the bind-property!");
			}
			String cardinality=attrs.getValue(ConfigTag.CARDINALITY);
			dealCardinalityTag(ref,cardinality);
			currentBundle.getReferences().add(ref);
		}
		private void dealPropertyTag(Attributes attrs){
			currentProperty=new Property();
			String name=attrs.getValue("name");
			String value=attrs.getValue("value");
			currentProperty.setName(name);
			currentProperty.setValue(value);
		}
		public void startElement (
    		    String uri,
    		    String sName,
    		    String qName,
    		    Attributes attrs)  {
			if (qName.equals(ConfigTag.COMPONENT)){
				dealComponentTag(attrs);
			}
			if (qName.equals(ConfigTag.SERVICE)){
				dealServiceTag(attrs);
			}
			if (qName.equals(ConfigTag.REFERENCE)){
				dealReferenceTag(attrs);
			}
			if (qName.equals(ConfigTag.PROPERTY)){
				dealPropertyTag(attrs);
			}
			if (qName.equals(ConfigTag.INTERCEPTOR)){
				this.dealInterceptorTag(attrs);
			}
		}
		public void endElement(String uri, String localName, String qName) 
        {
			if (qName.equals(ConfigTag.COMPONENT)){
			
				bundles.add(currentBundle);
			}
			if (qName.equals(ConfigTag.PROPERTY)){
				currentBundle.getProperties().add(currentProperty);
			}
			
        }
	}
	public void validate(InputStream configIs) {
		  try {
			   String strLang = XMLConstants.W3C_XML_SCHEMA_NS_URI;
			   SchemaFactory factory = SchemaFactory.newInstance(strLang);
			   InputStream isSchema = ClassLoader.getSystemResourceAsStream("mini-container.xsd");
			   StreamSource ss = new StreamSource(isSchema);
			   Schema schema = factory.newSchema(ss);	   
			   Validator validator = schema.newValidator();		   
			   StreamSource source = new StreamSource(configIs);
			   validator.validate(source);
		  } catch (Exception e) {
			  throw new LoadConfigException(e);
		  }
	}
	public void loadConfig(InputStream configIs) {		
		 Elementhnd handler = 	new Elementhnd();
		 try{
	      SAXParserFactory factory = SAXParserFactory.newInstance();	     
	      SAXParser saxParser = factory.newSAXParser();	
	      saxParser.parse( configIs ,handler);	     
	      configIs.close();
		 }catch(Exception e){
			 throw new LoadConfigException(e);
		 }
	}
	public List<ServiceBundle> getBundles(){
		return bundles;
	}
}
